package at.irian.jsfatwork.broker.web.model;

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import at.irian.jsfatwork.broker.domain.client.Client;
import at.irian.jsfatwork.broker.domain.client.ClientRepository;
import at.irian.jsfatwork.broker.domain.account.Accounting;

/**
 * @author Manfred Geiler
 */
@Component
@Scope("conversation.manual")
public class ClientAdministrationBean {

    @Autowired
    private ClientRepository clientRepository;

    @Autowired
    private Accounting accounting;

    /**
     * The current (edited) client
     */
    private Client client;


    public List<Client> getAllClients() {
        return clientRepository.getAllClients();
    }


    public Client getClient() {
        return client;
    }

    public void setClient(Client client) {
        this.client = client;
    }

    public String edit() {
        if (client == null) throw new IllegalStateException("No client set");
        return "edit";
    }

    @Transactional
    public String delete() {
        if (client == null) throw new IllegalStateException("No client set");
        accounting.deleteAllClientAccounts(client);
        clientRepository.delete(client);
        return "delete";
    }

    public String addNew() {
        client = clientRepository.createEmptyTransientClient();
        return "new";
    }

    @Transactional
    public String save() {
        clientRepository.save(client);
        return "save";
    }
}
